import React, { ReactElement, useState, useEffect, useImperativeHandle, forwardRef } from 'react'
import { Menu, Dropdown, Skeleton, Empty, Modal, message } from 'antd'
import { PlusOutlined, EllipsisOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import _ from 'lodash'
import style from './index.module.less'
import { getRoleListRequest, delRequst, getRuleListRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { RoleShcema } from '@src/components/schema/role'
import classNames from 'classnames'
import DetailModal from './components/detailModal'
import { AuthoritySchema } from '@src/components/schema/authority'
const { confirm } = Modal

async function delHandle (id: string, refreshData: () => void): Promise<void> {
  const [e] = await awaitWrap(delRequst(id))
  if (e === null) {
    message.success('删除成功').then(null, null)
    refreshData()
  }
}

function delConfirm (l: RoleShcema, refreshData: () => void): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: `您确定要删除 ${l.name} 吗？`,
    onOk: () => {
      delHandle(l.id, refreshData).catch(e => console.error(e))
    }
  })
}

async function initRuleList (setDesktops: (v: AuthoritySchema[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getRuleListRequest())
  if (e === null && d instanceof Array) {
    setDesktops(d)
  }
}

async function initData (currentRole: RoleShcema | null, setLoading: (v: boolean) => void, setRoleList: (v: RoleShcema[]) => void, setCurrentRole: (v: RoleShcema) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getRoleListRequest())
  setLoading(false)
  if (e === null && d instanceof Array) {
    setRoleList(d)
    if (d.length > 0) {
      if (currentRole === null) {
        setCurrentRole(d[0])
      } else {
        const index = d.map(li => li.id).indexOf(currentRole.id)
        if (index === -1) {
          setCurrentRole(d[0])
        } else {
          setCurrentRole(d[index])
        }
      }
    }
  }
}

interface ItemProps {
  data: RoleShcema
  currentRole: RoleShcema | null
  setCurrentRole: (v: RoleShcema) => void
  onEdit: (v: RoleShcema) => void
  refreshData: () => void
}

function Item ({ data, currentRole, setCurrentRole, onEdit, refreshData }: ItemProps): ReactElement {
  const menu = (
    <Menu>
      <Menu.Item key="0" onClick={() => onEdit(data)}>编辑</Menu.Item>
      <Menu.Item key="1" onClick={() => delConfirm(data, refreshData)}>删除</Menu.Item>
    </Menu>
  )
  return (
    <div className={classNames(style.item, { [style.active]: currentRole !== null && data.id === currentRole.id })} onClick={() => setCurrentRole(data)}>
      <span className={style['item-name']}>{data.name}</span>
      <Dropdown overlay={menu} trigger={['click']}>
        <span className={style['item-btn']} onClick={e => e.stopPropagation()}><EllipsisOutlined /></span>
      </Dropdown>
    </div>
  )
}

interface Props {
  currentRole: RoleShcema | null
  setCurrentRole: (v: RoleShcema) => void
}

export interface RoleListSchema {
  refreshData: () => void
  updateCurrentRoleRules: (rules: string[]) => void
}

// 更新当前角色的菜单
function updateCurrentRoleRules (currentRole: RoleShcema | null, setCurrentRole: (v: RoleShcema) => void, roleList: RoleShcema[], setRoleList: (v: RoleShcema[]) => void, rules: string[]): void {
  if (currentRole === null) {
    return undefined
  }
  const c = _.cloneDeep(currentRole)
  c.rules = rules
  setCurrentRole(c)
  const index = roleList.indexOf(currentRole)
  const l = [...roleList]
  if (index !== -1) {
    l.splice(index, 1, c)
  }
  setRoleList(l)
}

function Main ({ currentRole, setCurrentRole }: Props, ref: React.Ref<RoleListSchema>): ReactElement {
  const [loading, setLoading] = useState(false)
  const [roleList, setRoleList] = useState<RoleShcema[]>([])
  const [visible, setVisible] = useState(false)
  const [modifyData, setModifyData] = useState<RoleShcema|null>(null)
  const [desktops, setDesktops] = useState<AuthoritySchema[]>([])
  function refreshData (): void { initData(currentRole, setLoading, setRoleList, setCurrentRole).catch(e => console.error(e)) }
  useEffect(() => {
    refreshData()
    initRuleList(setDesktops).catch(e => console.error(e))
  }, [])
  useImperativeHandle(ref, () => {
    return {
      refreshData,
      updateCurrentRoleRules: (rules: string[]) => updateCurrentRoleRules(currentRole, setCurrentRole, roleList, setRoleList, rules)
    }
  })
  return (
    <div className={style.container}>
      <DetailModal visible={visible} data={modifyData} desktops={desktops} refreshData={refreshData} hide={() => { setModifyData(null); setVisible(false) }} />
      <div className={style.header}>角色列表</div>
      <Skeleton loading={loading} active>
        {roleList.map(li => {
          return <Item key={li.id} data={li} currentRole={currentRole} setCurrentRole={setCurrentRole} onEdit={(d) => { setModifyData(d); setVisible(true) }} refreshData={refreshData} />
        })}
        {roleList.length === 0 && !loading ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> : null}
      </Skeleton>
      <button className={style['add-btn']} onClick={() => { setModifyData(null); setVisible(true) }}>
        <PlusOutlined />
        <span className={style['add-btn-title']}>添加角色</span>
      </button>
    </div>
  )
}

export default forwardRef(Main)
